const express = require("express");
const router = express.Router();
const md5 = require("md5");
const db = require("../db");
const jwt = require("jsonwebtoken");

//注册接口
router.post("/reguser", async (req, res) => {
  let { username, password } = req.body;
  //对密码进行md5加密
  password = md5(password);
  //调用db
  const result = await db(`select * from user where username='${username}'`);
  if (result.length > 0) {
    //判断是否已注册
    res.send({ status: 1, message: "账号已存在" });
  } else {
    await db(
      `insert into user set username='${username}',password='${password}'`
    );
    res.send({ status: 0, message: "注册成功" });
  }
});

//登录接口
router.post("/login", async (req, res) => {
  let { username, password } = req.body;
  password = md5(password);
  const result = await db(
    `select * from user where username='${username}' and password='${password}'`
  );
  if (result.length > 0) {
    const token = jwt.sign({ id: result[0].id }, "coderlee", {
      expiresIn: "2h",
    });
    res.send({ status: 0, message: "登录成功", token: "Bearer " + token });
  } else {
    res.send({ status: 1, message: "登录失败" });
  }
});

module.exports = router;
